package org.sdsc.crms.web.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.sdsc.crms.entity.security.User;
import org.sdsc.crms.service.security.UserManager;
import org.sdsc.crms.web.CrudActionSupport;
import org.sdsc.modules.orm.Page;
import org.sdsc.modules.orm.PropertyFilter;
import org.sdsc.modules.orm.hibernate.HibernateWebUtils;
import org.sdsc.modules.web.struts2.Struts2Utils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数.
 * 
 * @author calvin
 */
@SuppressWarnings("serial")
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "user.action", type = "redirect") })
public class UserAction extends CrudActionSupport<User> {

	@Autowired
	private UserManager userManager;

	private User entity;
	private Long id;
	private Page<User> page = new Page<User>();

	public User getModel() {
		return entity;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Page<User> getPage() {
		return page;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = userManager.get(id);
		} else {
			entity = new User();
		}

	}

	// CRUD Action 函数 //
	@Override
	public String list() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		List<PropertyFilter> filters = HibernateWebUtils
				.buildPropertyFilters(request);
		page = userManager.search(page, filters);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		// 可以进行一些渲染页面的一些操作.
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		userManager.save(entity);
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		try {
			userManager.delete(id);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return RELOAD;
	}

	public String checkLoginName() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		String loginName = request.getParameter("loginName");
		String oldLoginName = request.getParameter("oldLoginName");
		 if (userManager.isLoginNameUnique(loginName, oldLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		return null;
	}

}
